import { Menu, Icon ,MenuItem,Submenu } from 'element-ui'
import { lrtokenGenerator } from '@/api/auth/auth'
import Cookies from 'js-cookie'
export default {
  name: 'TopNav',
  props: {
    theme: {
      type: String,
      required: false,
      default: 'dark'
    },
    mode: {
      type: String,
      required: false,
      default: 'horizontal'
    },
    collapsed: {
      type: Boolean,
      required: false,
      default: false
    }
  },
  data () {
    return {
      openKeys: [],
      selectedKeys: [],
      cachedOpenKeys: []
    }
  },
  computed: {
    rootSubmenuKeys: vm => {
      const keys = []
      vm.menu.forEach(item => keys.push(item.path))
      return keys
    },
    // 顶部显示菜单
    topMenus() {
      let topMenus = [];
      this.routers.map((menu) => {
        if (menu.hidden !== true) {
          // 兼容顶部栏一级菜单内部跳转
          if (menu.path === "/") {
            topMenus.push(menu.children[0]);
          } else {
            topMenus.push(menu);
          }
        }
      });
      return topMenus;
    },
    // 所有的路由信息
    routers() {
      console.log('topbarRouters======', this.$store.state.permission.topbarRouters)
      let topbarRouters = [...this.$store.state.permission.topbarRouters]
    //   topbarRouters.push({name:'OA系统',meta:{title:'OA系统',target:'_blank'},path:'https://doatest.envision-aesc.cn'})
        topbarRouters.push({name:'OA系统',meta:{title:'OA系统',target:'_blank'},path:'http://doa.envision-aesc.cn'})
      return topbarRouters;
    },
  },
  mounted () {
    this.updateMenu()
  },
  watch: {
    collapsed (val) {
      if (val) {
        this.cachedOpenKeys = this.openKeys.concat()
        this.openKeys = []
      } else {
        this.openKeys = this.cachedOpenKeys
      }
    },
    $route: function () {
      this.updateMenu()
    }
  },
  methods: {
    // select menu item
    onOpenChange (openKeys) {

      // 在水平模式下时执行，并且不再执行后续
      if (this.mode === 'horizontal') {
        this.openKeys = openKeys
        return
      }
      // 非水平模式时
      const latestOpenKey = openKeys.find(key => !this.openKeys.includes(key))
      if (!this.rootSubmenuKeys.includes(latestOpenKey)) {
        this.openKeys = openKeys
      } else {
        this.openKeys = latestOpenKey ? [latestOpenKey] : []
      }
    },
    updateMenu () {
      const routes = this.$route.matched.concat()
      const { hidden } = this.$route.meta
      if (routes.length >= 3 && hidden) {
        routes.pop()
        this.selectedKeys = [routes[routes.length - 1].path]
      } else {
        this.selectedKeys = [routes.pop().path]
      }
      const openKeys = []
      if (this.mode === 'inline') {
        routes.forEach(item => {
          openKeys.push(item.path)
        })
      }
      if(!this.selectedKeys || this.selectedKeys[0].indexOf(":")<0){
        this.collapsed ? (this.cachedOpenKeys = openKeys) : (this.openKeys = openKeys)
      }
    },

    // render
    renderItem (menu) { //system  //log // Operlog
      if (!menu.hidden) {
        return menu.children && menu.alwaysShow ? this.renderSubMenu(menu) : this.renderMenuItem(menu)
      }
      return null
    },
    async toOutLink(e) {
        e.stopPropagation()
        e.preventDefault()
        const result = await lrtokenGenerator()
        console.log(result,'==============SsoLoginToken')
        Cookies.set('SsoLoginToken', result.data, { domain: '.envision-aesc.cn', path: '/', expires: 7200 })
        // document.cookie = "SsoLoginToken="+result.data+";expires=7200;domain=.envision-aesc.cn;path=/"
        // location.href = "https://doatest.envision-aesc.cn"
        location.href = "http://doa.envision-aesc.cn"
    },
    renderMenuItem (menu) {
      const target = menu.meta.target || null
      let tag = target && 'a' || 'router-link'
      menu.path = (menu.path.includes('/')?menu.path:`/${menu.path}`)
      let props = { to: { path: menu.path }}
      const attrs = { href: menu.path,  target: target }
      console.log(menu.path)
      if (menu.children && menu.alwaysShow) {
        // 把有子菜单的 并且 父菜单是要隐藏子菜单的
        // 都给子菜单增加一个 hidden 属性
        // 用来给刷新页面时， selectedKeys 做控制用
        menu.children.forEach(item => {
          item.meta = Object.assign(item.meta, { hidden: true })
        })
      }
      return (
        <MenuItem {...{ key: (menu.name + menu.path),index: menu.path }} >
              <tag {...{ props, attrs }} style={{ display: 'block' }} v-on:click={($event)=>this.toOutLink($event)}>
            {/*{this.renderIcon(menu.meta.icon)}*/}
            {menu.meta.title}
          </tag>
        </MenuItem>
      )
    },
    renderSubMenu (menu) {
      const itemArr = []
      if (menu.alwaysShow) {
        menu.children.forEach(item => itemArr.push(this.renderItem({...item, path: `${menu.path}/${item.path}`})))
      }
      return (
        <Submenu {...{ key: menu.path }} index={menu.path} >
          <span slot="title">
            {/*{this.renderIcon(menu.meta.icon)}*/}
            {menu.meta.title}
          </span>
          {itemArr}
        </Submenu>
      )
    },
    renderIcon (icon) {
      if (icon === 'none' || icon === undefined) {
        return null
      }
      const props = {}
      typeof (icon) === 'object' ? props.component = icon : props.type = icon
      return (
         <svg-icon icon-class={icon} style={{marginRight:'8px'}}/>
      )
    }
  },

  render () {
    const { mode, theme, topMenus } = this
    const props = {
      mode: mode,
      theme: theme,
      openKeys: this.openKeys,
    }
    const on = {
      select: obj => {
      //   this.selectedKeys = obj.selectedKeys
        this.$emit('select', obj)
      },
      openChange: this.onOpenChange
    }

    const menuTree = topMenus.map(item => {
      if (item.hidden) {
        return null
      }
      return this.renderItem(item)
    })
    // {...{ props, on: on }}
    return (
      <Menu  vModel={this.selectedKeys} {...{ props, on: on }}  style={{background:'transparent',border:0}}>
        {menuTree}
      </Menu>
    )
  }
}
